package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.entity.News;
import com.example.mapper.NewsMapper;
import com.example.qo.NewsQuery;
import com.example.service.INewsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xs
 * @since 2023-04-13
 */
@Service
public class NewsServiceImpl extends ServiceImpl<NewsMapper, News> implements INewsService {

    @Autowired
    private NewsMapper newsMapper;


    @Override
    public Page<News> queryPage(NewsQuery qo) {
        Page<News> pageParam = new Page<>();
        pageParam.setCurrent(qo.getCurrent());
        pageParam.setSize(qo.getSize());
        QueryWrapper<News> qw = new QueryWrapper();
        return newsMapper.selectPage(pageParam,qw);
    }

    @Override
    public void updateViewNum(long id, long viewnum) {
        UpdateWrapper<News> uw = new UpdateWrapper<>();
        uw.eq("id",id);
        uw.set("viewnum",viewnum);
        newsMapper.update(null,uw);
    }

    @Override
    public List<Map<String, Object>> queryRanks(NewsQuery nqo) {
        Page<News> pageNews = this.queryPage(nqo);
        List<News> news = pageNews.getRecords();
        for (News n : news) {
            QueryWrapper<News> qw = new QueryWrapper();
            qw.eq("create_time",n.getCreateTime());
            qw.orderByDesc("count");
            List<News> news1 = newsMapper.selectList(qw);
            for (News news2 : news1) {
                long i = 0;
                news2.setRank(i);
            }
        }

        QueryWrapper<News> qw = new QueryWrapper<>();
        qw.groupBy("history_id");
        qw.select("history_id,GROUP_CONCAT(DISTINCT rank) ranks");
        List<Map<String, Object>> maps = newsMapper.selectMaps(qw);
        return maps;
    }
}
